/*
 * @Author:
 * @Date: 2022-11-04 16:33:02
 * @LastEditTime: 2023-03-29 10:10:55
 * @LastEditors: ***
 * @Description:
 */
import { useMemo } from 'react';
// useHistory, useRouteMatch
import { history, useLocation, useParams, useRouteData } from 'umi';

export function getUrlParams(url: string) {
  if (!url) return {};
  let search: string = '';
  if (url.search('#') !== -1) {
    search = url.substring(url.indexOf('#') + 1);
  } else {
    search = url.substring(url.indexOf('?') + 1);
  }
  return search.split('&').reduce<{ [key: string]: string }>((params, search) => {
    const [key, value] = search.split('=');
    params[key] = value;
    return params;
  }, {});
}

function useRouter() {
  const params = useParams();
  const location = useLocation();
  // const history = useHistory();
  const match = useRouteData();
  return useMemo(() => {
    return {
      push: history.push,
      replace: history.replace,
      pathname: location.pathname,
      query: {
        ...getUrlParams(location.search),
        ...params,
      } as { [key: string]: any },
      match,
      location,
      history,
    };
  }, [
    params,
    match,
    location,
    location.pathname,
    history,
    window.localStorage.getItem('language'),
  ]);
}

export default useRouter;
